package com.shycloud.mido.organ.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.organ.api.entity.MemberEntity;
import com.shycloud.mido.organ.api.entity.MiniInteraction;
import com.shycloud.mido.organ.api.entity.WorksComment;
import com.shycloud.mido.organ.api.entity.WorksEntity;
import com.shycloud.mido.organ.api.vo.WorksEntityVO;
import com.shycloud.mido.organ.mapper.InteractionMapper;
import com.shycloud.mido.organ.mapper.MemberMapper;
import com.shycloud.mido.organ.mapper.MiniFollowedMapper;
import com.shycloud.mido.organ.mapper.MiniWorksZanMapper;
import com.shycloud.mido.organ.mapper.WorksCommentMapper;
import com.shycloud.mido.organ.mapper.WorksMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
@RequestMapping("/works")
public class WorksController {

	private WorksMapper worksMapper;
	private WorksCommentMapper worksCommentMapper;
	private MiniWorksZanMapper worksZanMapper;
	private MemberMapper memberMapper;
	private MiniFollowedMapper followedMapper;
	private InteractionMapper interactionMapper;

	//获取推荐作品
	@GetMapping("/getRecommendedWorks")
	public R getRecommendedWorks(Integer size, String memberId) {

		if (size == null || size == 0) {
			size = 10;
		}
		List<WorksEntity> res = new ArrayList<>();

		while (res.size() == 0) {
			List<WorksEntityVO> recommendedWorks = worksMapper.getRecommendedWorks(size, memberId);


			if (StringUtils.isEmpty(memberId)) {
				res = recommendedWorks.stream().filter(x -> x.getPermission() == 0).collect(Collectors.toList());
			} else {

				for (WorksEntityVO recommendedWork : recommendedWorks) {

					if (recommendedWork.getPermission() == 1) {
						//判断此人是否与用户是好友关系
						if (isFriend(recommendedWork.getMemberId(), memberId)) {
							res.add(recommendedWork);
						}
					} else {
						res.add(recommendedWork);
					}
				}
			}
		}

		return new R<>(res);
	}

	//获取关注推荐作品
	@GetMapping("/getFollowedWorks")
	public R getFollowedWorks(String memberId, Integer size) {
		if (size == null || size == 0) {
			size = 10;
		}
		return new R<>(worksMapper.getFollowedWorks(memberId, size));
	}

	//获取作品详情
	//包括: 作者名字, 收藏/点赞数量/状态, 评论数量(点赞自动收藏, 没有收藏操作, 二者数量等同)
	@GetMapping("/getWorksDetail")
	public R getWorksDetail(String memberId, String worksId) {

		Map<String, Object> result = new HashMap<String, Object>();
		//先查询作品信息
		WorksEntity works = worksMapper.selectById(worksId);
		MemberEntity member = memberMapper.selectById(works.getMemberId());
		result.put("name", member.getShowname());
		result.put("avatar", member.getAvatar());
		//查询点赞数量
		QueryWrapper zanQuery = new QueryWrapper();
		zanQuery.eq("works_id", worksId);
		Integer zanNumber = worksZanMapper.selectCount(zanQuery);
		result.put("zanNumber", zanNumber);
		//查询评论数量
		QueryWrapper commentQuery = new QueryWrapper();
		commentQuery.eq("works_id", worksId);
		Integer commentNumber = worksCommentMapper.selectCount(commentQuery);
		result.put("commentNumber", commentNumber);
		//查询点赞状态
		if (memberId == null) {
			result.put("zanStatus", false);
		} else {
			QueryWrapper zanStatusQuery = new QueryWrapper();
			zanStatusQuery.eq("works_id", worksId);
			zanStatusQuery.eq("member_id", memberId);
			if (worksZanMapper.selectCount(zanStatusQuery) == 0) {
				result.put("zanStatus", false);
			} else {
				result.put("zanStatus", true);
			}
		}

		//查询关注状态
		if (memberId == null) {
			result.put("followStatus", false);
		} else {
			QueryWrapper followStatusQuery = new QueryWrapper();
			followStatusQuery.eq("member_id", memberId);
			followStatusQuery.eq("to_member_id", works.getMemberId());
			if (followedMapper.selectCount(followStatusQuery) == 0) {
				result.put("followStatus", false);
			} else {
				result.put("followStatus", true);
			}
		}
		return new R<>(result);
	}

	@GetMapping("/getWorksByMemberId")
	public R getWorksByMemberId(Page<WorksEntity> page, String myMemberId, String otherMemberId) {
		//需要判定关注关系
		IPage<WorksEntity> result = new Page();
		if (isFriend(myMemberId, otherMemberId)) {
			result = worksMapper.getFriendWorks(page, otherMemberId);
		} else {
			result = worksMapper.getNoFriendWorks(page, otherMemberId);
		}
		return new R<>(result);
	}

	@PostMapping("/addWorks")
	public R addWorks(@RequestBody WorksEntity works) {

		String memberId = works.getMemberId();
		MemberEntity memberEntity = memberMapper.selectById(memberId);

		if ("1".equals(memberEntity.getMiniStatus())) {
			return new R(CommonConstants.FAIL, "您的账号已被禁用，请联系客服电话 4000123485 进行处理。", false);
		}
		int result = worksMapper.insert(works);
		return new R<>(result);
	}

	@GetMapping("/getMyWorks")
	public R getMyWorks(Page<WorksEntity> page, String memberId, String status) {

		String[] statusArr = status.split(",");

		return new R<>(worksMapper.getMyWorks(page, memberId, statusArr));
	}

	@Transactional
	@GetMapping("/deleteById")
	public R deleteById(int id) {

		List<WorksComment> worksComments = worksCommentMapper.selectList(new QueryWrapper<WorksComment>()
				.eq("works_id", id));

		interactionMapper.delete(new QueryWrapper<MiniInteraction>().eq("target_id", id));

		worksCommentMapper.delete(new QueryWrapper<WorksComment>().eq("works_id", id));

		int result = worksMapper.deleteById(id);
		return new R<>(result);
	}

	@Transactional
	@PostMapping("/addComment")
	public R addComment(@RequestBody WorksComment comment) {

		String memberId = comment.getMemberId();
		MemberEntity memberEntity = memberMapper.selectById(memberId);

		if ("1".equals(memberEntity.getMiniStatus())) {
			return new R(CommonConstants.FAIL, "您的账号已被禁用，请联系客服电话 4000123485 进行处理。", false);
		}

		int result = 0;
		if (!comment.getFatherId().equals("-1")) {
			//当回复某条评论时, 更新父评论状态
			WorksComment father = worksCommentMapper.selectById(comment.getFatherId());
			father.setHasChild(1);
			worksCommentMapper.updateById(father);
		}
		result += worksCommentMapper.insert(comment);
		//增加互动信息
		MemberEntity member = memberMapper.selectById(comment.getMemberId());
		WorksEntity works = worksMapper.selectById(comment.getWorksId());
		MiniInteraction interaction = new MiniInteraction();
		interaction.setFromMemberId(comment.getMemberId());
		interaction.setFromMemberName(member.getShowname());
		interaction.setCommentId(comment.getId());
		interaction.setType(1);
		interaction.setToMemberId(works.getMemberId());
		interaction.setTargetId(comment.getWorksId());
		interaction.setText(member.getShowname() + "评论了您的作品");
		result += interactionMapper.insert(interaction);
		return new R<>(result);
	}

	@GetMapping("/getComment")
	public R getComment(Page<WorksComment> page, String worksId) {
		return new R<>(worksCommentMapper.getComment(page, worksId));
	}

	@GetMapping("/getCommentDetail")
	public R getCommentDetail(Page<WorksComment> page, String worksId, String fatherId) {
		return new R<>(worksCommentMapper.getCommentDetail(page, worksId, fatherId));
	}

	//判断是否为好友
	private Boolean isFriend(String myMemberId, String otherMemberId) {
		//互相关注即为好友
		QueryWrapper from = new QueryWrapper<>();
		from.eq("member_id", otherMemberId);
		from.eq("to_member_id", myMemberId);
		Integer fromNum = followedMapper.selectCount(from);

		QueryWrapper to = new QueryWrapper<>();
		to.eq("member_id", myMemberId);
		to.eq("to_member_id", otherMemberId);
		Integer toNum = followedMapper.selectCount(to);

		if (fromNum != 0 && toNum != 0) {
			return true;
		} else {
			return false;
		}
	}

}
